package com.ticket.sass.provider.dto.output.resource;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ticket.sass.common.entity.tenant.ResourceEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ywb
 * @date 2022-01-07 15:34
 */
@Data
@ApiModel(value = "资源")
public class ResourceListOutput implements Comparable<ResourceListOutput> {
    @ApiModelProperty(value = "ID")
    private Integer id;

    @ApiModelProperty(value = "排序")
    private Integer sort;

    @ApiModelProperty(value = "资源名")
    private String name;

    @ApiModelProperty(value = "资源等级")
    private Integer level;

    @ApiModelProperty(value = "父类id 0 最高级")
    private Integer parentId;

    @ApiModelProperty(value = "备注")
    private String remark;

    @ApiModelProperty(value = "权限标识符")
    private String perms;
    
    @ApiModelProperty(value = "数据")
    private Map<String, Object> data;
    
    // 静态方法将 ResourceEntity 转换为 ResourceListOutput
    public static ResourceListOutput fromEntity(ResourceEntity entity) {
        ResourceListOutput output = new ResourceListOutput();
        output.setId(entity.getId());
        output.setSort(entity.getSort());
        output.setName(entity.getName());
        output.setLevel(entity.getLevel());
        output.setParentId(entity.getParentId());
        output.setRemark(entity.getRemark());
        output.setPerms(entity.getPerms());
        
        // 将 JSON 字符串转换为 Map
        if (entity.getData() != null) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> dataMap = objectMapper.readValue(entity.getData(), new TypeReference<>() {
                });
                output.setData(dataMap);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                // 处理 JSON 解析异常
                output.setData(new HashMap<>());
            }
        } else {
            output.setData(new HashMap<>());
        }
        
        return output;
    }
    
    public ResourceListOutput() {
    }

    @Override
    public int compareTo(@NotNull ResourceListOutput o) {
        return this.sort.compareTo(o.getSort());
    }
    
    
    
}
